define(["jquery", "bbcare", "oms_config/root", "fu/app/comm/page/page",
	"fu/app/outPatient/outPatientList.servers",
	"fu/app/outPatient/outPatientList.ui",
], function ($, $bb, $root, $page, $servers, $ui) {
	var outPatientList = {}

	/**
	 * 按科研编号、手机号、姓名搜索患者时，传参有所不同
	 */
	var searchKeywordAjax = function (params) {
		var reg = /^1\d{10}$/
		if (reg.test(params.fuzzyVar)) {
			$.extend(params, { phoneNum: params.fuzzyVar })
		} else {
			delete params.phoneNum
		}
		$servers.ajaxPatientsQueue(params, ajaxPatientsQueueCallBack)
	}
	/**
	 * 输入姓名、手机号、科研编号进行搜索
	 */
	var onKeywordClick = function () {
		var params = $(this).data()
		$(this).prev().val("")
		var keyword = $(this).prev().val()
		$.extend(params, { "page": 1, "fuzzyVar": keyword })
		searchKeywordAjax(params)
	}
	var onKeywordInput = function () {
		var params = $(this).data()
		var keyword = $(this).val()
		$.extend(params, { "page": 1, "fuzzyVar": keyword })
		searchKeywordAjax(params)
	}

	/**
	 * 点击患者卡片进入详情页
	 */
	var onBabyCardClick = function () {
		var followQueueId = $(this).attr("followQueueId")
		var patientSchemeId = $(this).attr("patientSchemeId")
		var patientId = $(this).attr("patientId")
		var imgSrc = $(this).find(".clickbabycard-icon").find("img").attr("src")
		var patientName = $(this).find(".clickbabycard-name").text()
		var queuename = $(this).find(".clickbabycard-queuename").text()
		var params = {
			patientSchemeId: patientSchemeId,
			followQueueId: followQueueId,
			patientName: patientName,
			imgSrc: imgSrc,
			queuename: queuename,
			patientId: patientId
		}
		// console.log("99999999",params)
		$bb.openPage("outPatient", params)
	}

	/**
	 * 请求患者接口成功后的回调函数
	 */
	var ajaxPatientsQueueCallBack = function (data, params) {
		if (data.rows && data.rows.length > 0) {
			$("#outPatientList-tit").html(data.rows[0].followQueueName + "患者")
			var pagesAll = Math.ceil(data.total / params.rows)
			$ui.babyListInit({
				id: "babyList",
				list: data.rows,
				rows: params.rows
			})
			/* 翻页 */
			$page.turnInit({
				id: "page",
				pagesAll: pagesAll,
				page: params.page
			}, $servers.ajaxPatientsQueue, params, ajaxPatientsQueueCallBack)
			/* 点击随访患者卡片进入详情页 */
			$("#babyList .clickbabycard").unbind("click")
			$("#babyList .clickbabycard").click(onBabyCardClick)
		} else {
			if (data && data.followQueueName) {
				$("#outPatientList-tit").html(data.followQueueName + "患者")
			}
			$("#babyList").html('<div class="col-sm-12 col-md-12 babycard-null">暂无数据..</div>')
			$("#page").html("")
		}
		/* 姓名、科研编号、手机号码查询 */
		$("#searchPatient span").unbind("click")
		$("#searchPatient span").data(params)
		$("#searchPatient span").click(onKeywordClick)
		$("#searchPatient input").unbind("input propertychange")
		$("#searchPatient input").data(params)
		$("#searchPatient input").bind("input propertychange", onKeywordInput)
	}

	/**
	 * 跳转到新建患者页面
	 */
	var onAddPatient = function () {
		var params = $(this).data("params")
		if (!params) {
			params = {
				followQueueId: $servers.getPageParams().followQueueId
			}
		}
		var config = $root.init()
		$bb.openPage(config.route.outPatientListAddPatient, params)
	}

	/**
	 * 初始化
	 */
	outPatientList.init = function () {

		getWindowConfigAndSetGlobal()

		var queueId = $servers.getPageParams().followQueueId
		var topbars = [
			{
				"icon": "fa fa-plus",
				"name": "新建患者",
				"callback": onAddPatient,
				"params": {
					"followQueueId": queueId
				}
			}
		]
		// 是否显示转队列
		if (window.__config__.__is_show_relation__) {
			var relation = {
				"icon": "fa fa-chain",
				"name": "关联其他队列患者",
				"callback": patient_relation,
			}
			topbars.push(relation)
		}
		if (window.__config__.role.indexOf('ReadOnly') == -1) {
			$bb.toolbar(topbars)
		}

		var rows
		if (document.body.offsetWidth < 992) {
			rows = 2
		} else if (document.body.offsetWidth < 1200) {
			rows = 3
		} else {
			rows = 4
		}
		var params = {
			"page": 1,
			"rows": rows * 5,
			"flag": "2",
			"systemType": "00",
			"queueId": queueId
		}
		$servers.ajaxPatientsQueue(params, ajaxPatientsQueueCallBack)
	}

	/**
	 * 查看全局配置并且暂存到全局 Global 对象
	 * 因为 window._config 会被覆盖
	 */
	var getWindowConfigAndSetGlobal = function () {
		try {
			var config = JSON.parse(window._config)
			window.__global__ = window.__global__ ? window.__global__ : {}
			for (var key in config) {
				window.__global__[key] = config[key]
			}
		} catch (err) {
			console.log('获取 window.config 失败')
		}
	}


	/**
	 * 2020年10月28日新增 关联患者和新建患者事件
	 */
	var patient_relation = function () {
		$('._new_mask_').css('display', 'block')
	}

	var patient_create = function () {
		$bb.selectNavbar("addPatient")
	}
	var checkedPatients = []
	// $('#content-main').on('click', '#_out_patient_relation_', patient_relation)
	// $('#content-main').on('click', '#_out_patient_create_', onAddPatient)
	$('#content-main').on('click', '._new_mask_', function (e) {
		if (e.target.className === '_new_mask_') {
			// $(this).css('display', 'none')
		}
	})
	// 点击关闭弹窗
	$('#content-main').on('click', '.close', function (e) {
		if (e.target.className === 'close' || e.target.className.indexOf('fa-times') > -1) {

			$('._new_mask_').hide()
			$('.addNewPatient').text('请搜索并添加患者')
			checkedPatients = undefined
			clearAllChecked()
		}
	})
	// 搜索名字或号码获取用户
	$('#content-main').on('input propertychange', '#_patient_search_input', function () {
		$('.addNewPatient').text('搜索中...')
		searchPatient(this)
	})

	var __timer = undefined
	var searchPatient = function (el) {
		if (__timer) clearTimeout(__timer)
		__timer = setTimeout(function () {
			var context = $(el).val()
			if (context === '') return
			var params = {}
			if (typeof Number(context) !== 'NaN' && context.length === 11) {
				params.phoneNo = context
			} else {
				params.patientName = context
			}
			$servers.searchPatient(params, searchPatientCallBack)
		}, 500)
	}

	// 点击下一步
	$('#content-main').on('click', '#_patient_next', function () {
		if (!checkedPatients || checkedPatients.length === 0) return $bb.toastShow('请选择一个患者')
		var params = {
			patientId: checkedPatients.id,
			followQueueId: $servers.getPageParams().followQueueId,
			name: checkedPatients.userName
		}
		$servers.copyPatient(params, copyPatientCallBack)
	})

	var searchPatientCallBack = function (result, params) {
		$(".table-wrapper").off("click")
		$('#_patient_table').remove()
		$('.addNewPatient').hide()
		var tr_html = ''
		for (var i = 0; i < result.length; i++) {
			tr_html += '<tr class="hover" data-index="' + i + '" >' +
				'<td><span class="patient_input" data-index="' + i + '"></span></td>' +
				'<td>' + result[i].userName + '</td>' +
				'<td>' + (result[i].gender.indexOf('N') > -1 ? '男' : '女') + '</td>' +
				'<td>' + result[i].birthday + '</td>' +
				'<td style="text-align: left;">' + result[i].queueName + '</td>' +
				'<td>' + result[i].phoneNo + '</td>' +
				'</tr>'
		}
		var table_html = '<table id="_patient_table">' +
			'<tr class="header">' +
			'<th style="width: 48px;"></th>' +
			'<th style="width: 70px;">患者姓名</th>' +
			'<th style="width: 43px;">性别</th>' +
			'<th style="width: 110px;">出生日期</th>' +
			'<th style="width: 177px;">所属队列</th>' +
			'<th style="width: 108px;">联系电话</th>' +
			'</tr>' +
			tr_html +
			'</table>'

		if (result.length > 0) {
			$('.table-wrapper').append(table_html)
		} else {
			$('.addNewPatient').text('未找到相关人员').show()
		}

		$('.table-wrapper').on('click', '.hover', function (e) {
			var input = $(this).find('.patient_input')[0]
			var index = $(this).data('index')
			if ($(input).attr("class").indexOf('patient_checked') === -1) {
				clearAllChecked()
				$(input).addClass('patient_checked')
				checkedPatients = result[index]
			} else {
				clearAllChecked()
				checkedPatients = undefined
			}
		})

	}

	function clearAllChecked () {
		// 清除所有选中效果
		var allInputs = $('.patient_input')
		for (var o = 0; o < allInputs.length; o++) {
			$(allInputs[o]).removeClass('patient_checked')
		}
	}

	var copyPatientCallBack = function (result, params) {
		if (result.success) {
			$bb.toastShow('关联成功')
			$('.close').click()
			outPatientList.init()
		}
	}


	return outPatientList
})
